import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/FandCar/DriverIntroduction.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../SendGoods/MatureCarList.dart';
import '../TabBar/TabbarView.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'SelectSourceOfGoods.dart';
import 'package:platform/platform.dart';
class DesignatedDriverView extends StatefulWidget {
  const DesignatedDriverView({super.key, required this.goodsMap, required this.findType,});
  final Map goodsMap;
  final int findType;
  @override
  State<DesignatedDriverView> createState() => _DesignatedDriverViewState();
}

class _DesignatedDriverViewState extends State<DesignatedDriverView> {
  FocusNode focusNode = FocusNode();
  BrnSearchTextController scontroller = BrnSearchTextController();
  TextEditingController textController = TextEditingController();
  List dataList=[];
  Map goodsMap={};
  @override
  void initState() {
    textController.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
          scontroller.isActionShow = true;
        }
      }
    });
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        if (!BrunoTools.isEmpty(textController.text)) {
          scontroller.isClearShow = true;
        }
      }
    });
    super.initState();
    // getEmptyCarListAction();
    getLocCarListAction();
    if(widget.findType==2){
      goodsMap=widget.goodsMap;
      print(goodsMap);
    }
  }
  void  getLocCarListAction()async{
    List? Drivers=[];
    Drivers=await HisDriverPhoneManager.getDriverPhone();
    print(Drivers);
    if(Drivers!.isNotEmpty) {
      for (int i = 0; i < Drivers.length; i++) {
        NoLoadinggetApiManager.getData(
          context,
          "api/auth/driver/user/getUserByPhone",
          {'phoneNum':Drivers[i]},
              (responseData)  {
            setState(() {
              dataList.add(responseData['data']);

            });
          },
        );
      }
    }
  }
  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        showCallPhoneFirstDialog(context);
        // 权限被拒绝，但用户可以再次授权
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }

  getEmptyCarListAction() async {
    ApiManager.postData(
      context,
      'api/user/shpr/user/searchAirCarList',
      {
        "pageSize":20,
        "pageNum":1,
        "createTime":1,
      },
          (responseData) {
            setState(() {
              dataList =responseData['data']['records'];
            });
      },
    );
  }
  Future<void> reCommonWaybillAction(String drvId) async {
    ApiManager.postData(
      context,
      'api/waybill/waybill/common/cancelWaybill',
      {
        // "waybillId":widget.orderId,
        "cancelStatus":2,
        "drvId":drvId
      },
          (responseData) {
            Navigator.pop(context);
      },
    );

  }
  void uploadGoodsAction(String drvId){
    goodsMap['drvId']=drvId;
    goodsMap['dispatchStatus']=1;
    LoadingDialog.show(context);
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) async {
          options.headers["satoken"] = await TokenManager.getToken();
          options.headers["loginType"] = "shipper";
          return handler.next(options);
        }
    ));
    dio
        .post(
      MyServiceUrl.header +
          'api/goods/goods/goods/add',
      data:widget.goodsMap,
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) =>
          print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          print("code：$code");
          LoadingDialog.hide(context);
          BrnDialogManager.showConfirmDialog(context,
              title: "发布成功,是否再发一单？",
              cancel: "",
              cancelWidget: GestureDetector(
                child: Center(
                  child: Text("返回",
                    style: TextStyle(
                        color: Colors.black),),
                ),
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                      builder: (context) =>
                          TabbarView(pateIndex: 0,),
                      fullscreenDialog: true,),
                  );
                },
              ),
              conformWidget: GestureDetector(
                child: Center(
                  child: Text("再发一单",
                    style: TextStyle(
                        color: MyColors.themeColor),),
                ),
                onTap: () {
                  Navigator.pop(context);
                  Navigator.pop(context);
                },
              ),
              confirm: "",
              onConfirm: () {
                Navigator.pop(context);
              },
              onCancel: () {


              });
        } else {
          LoadingDialog.hide(context);
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  void searchDriverAction(String drvPhoneNum,String vehicleNum) async {
    NoLoadinggetApiManager.getData(
      context, // 上下文对象，用于显示提示信息等
      'api/auth/driver/user/getSearchUser', // 您的API端点key
      {"key":drvPhoneNum+vehicleNum}, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
          dataList=responseData['data'];
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar:widget.findType==2? AppBar(
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("指派司机",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ):null,
      body:ListView(
        children: [

        if(widget.findType!=2)
          Container(
            margin: EdgeInsets.only(top: 8.h,left: 15.w,right: 15.w,),
            padding: EdgeInsets.only(left: 20.w,right: 10.w),
            decoration: BoxDecoration(
                color: Color.fromRGBO(251, 236, 228, 1),
                borderRadius: BorderRadius.all(Radius.circular(10))),
            height: 30.h,
            child:GestureDetector(
              child:    Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Image.asset("lib/Images/OrderList/去指派熟车icon.png",width: 20.w,height: 20.h,),
                      SizedBox(width: 8.w,),
                      Text("去指派我的熟车",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                    ],
                  ),
                  Icon(Icons.arrow_forward_ios,color: MyColors.themeColor,size: 20,),
                ],
              ),
              onTap: () async {
                String? shippedId =await UserIdManager.getUserID();
                Navigator.push( context, FadeRoute(page:MatureCarList(
                  orderId:"" , shipperId:shippedId!,
                )));

              },
            ),

          ),
          Container(
            height:40.h,
            child:   BrnSearchText(
              focusNode: focusNode,
              controller: textController,
              searchController: scontroller..isActionShow = false,
              outSideColor: MyColors.backgreyColor,
              innerColor: Colors.white,
              borderRadius: BorderRadius.all(const Radius.circular(10.0)),
              hintText: "输入司机手机号码/车牌号",
              onTextClear: () {
                debugPrint('sss');
                return false;
              },
              autoFocus: false, // 将这里设置为 false 来关闭自动获取焦点
              onActionTap: () {
                scontroller.isClearShow = false;
                scontroller.isActionShow = false;
                focusNode.unfocus();

              },
              onTextCommit: (text) {

              },
              onTextChange: (text) {
                if (text.contains(RegExp(r'[a-zA-Z]')) && text.length > 0) {
                  searchDriverAction(text, "");
                } else {
                  searchDriverAction("", text);
                }
              },
            ),
          ),
          // Text("此列表仅显示最近30天指派过的司机",style: TextStyle(color: MyColors.hintColor,fontSize: 12.sp),),
          Container(
            margin: EdgeInsets.only(left: 10.w,right: 10.w,),
            height: screenSize.height-300.h,
            child: ListView.builder(
                shrinkWrap:false,
                itemCount:dataList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    decoration: BoxDecoration(
                        color:Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(10))),
                    margin: EdgeInsets.only(bottom: 8.h),
                    padding: EdgeInsets.only(left:15.w,right: 15.w,top: 10.h,bottom: 10.h),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Container(
                                  width: 36.w,
                                  height: 36.h,
                                  child:  dataList[index]['avatarPath']!=null&&dataList[index]['avatarPath']!=""?
                                  CircleAvatar(
                                    radius: 15,
                                    backgroundImage: NetworkImage(MyServiceUrl.imgHeader +dataList[index]['avatarPath']),
                                  )
                                      :  CircleAvatar(
                                    radius: 15,
                                    backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                                  ),
                                ),


                                SizedBox(width: 8.w,),
                                Text(dataList[index]['realName'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 16.sp),),
                              ],
                            ),

                            // BrnTagCustom.buildBorderTag(
                            //   tagText: dataList[index]['qualificationCertificateStatus']!=2?'三证齐全':'五证齐全',
                            //   textColor: MyColors.themeColor,
                            //   borderColor: MyColors.themeColor,
                            //   borderWidth: 1.w,
                            //   fontSize: 11.sp,
                            // )
                          ],
                        ),
                        SizedBox(height: 8.h,),
                        Text(dataList[index]['vehicleNum'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 16.sp)),
                        SizedBox(height:4.h,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Container(
                                    width: 200.w,
                                    child:dataList[index]['vehicleLength']!=null? Text(dataList[index]['vehicleLength'].toString()+"丨"+dataList[index]['vehicleModel'].toString()+"  "+dataList[index]['vehicleTonnage'].toString()+"吨",style: TextStyle(overflow:  TextOverflow.ellipsis,color: MyColors.textColor,fontSize: 13.sp),)
                                :SizedBox())
                              ],
                            ),
                            RichText(
                              text: TextSpan(
                                text: '好评率 ', // 第一部分文本
                                style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),
                                children: [
                                  TextSpan(
                                    text:dataList[index]['rating']!=null? dataList[index]['rating'].toString()+"%":"--"+'%', // 第二部分文本
                                    style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                        Divider(
                          height: 10.h,
                          color: MyColors.backgreyColor,
                        ),
                        Container(
                          height:30.h,
                          child:  Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              GestureDetector(
                                child:  BrnTagCustom.buildBorderTag(
                                  tagText: '指定承运',
                                  textColor: MyColors.themeColor,
                                  borderColor: MyColors.themeColor,
                                  fontWeight: FontWeight.w600,
                                  borderWidth: 1,
                                  fontSize: 12.sp,
                                  tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                  textPadding: EdgeInsets.all(6),
                                ),
                                onTap: (){
                                  if(widget.findType==2){
                                    ApiManager.postData(
                                      context,
                                      'api/waybill/shipper/waybill/addAndAssign',
                                      {
                                        "companyId":widget.goodsMap['companyId'],
                                        "orgId": widget.goodsMap['orgId'],
                                        "shipperId": widget.goodsMap['shipperId'],
                                        "category": widget.goodsMap['category'],
                                        "invoiceType": widget.goodsMap['invoiceType'],
                                        "loadPlaceInfo": widget.goodsMap['loadPlaceInfo'],
                                        "unloadPlaceInfo": widget.goodsMap['unloadPlaceInfo'],
                                        "loadDay": widget.goodsMap['loadDay'],
                                        "loadTime": widget.goodsMap['loadTime'],
                                        "unloadDay": widget.goodsMap['unloadDay'],
                                        "unloadTime": widget.goodsMap['unloadTime'],
                                        "cargoInfo": widget.goodsMap['cargoInfo'],
                                        "vehicleLength":widget.goodsMap['vehicleLength'],
                                        "vehicleModel": widget.goodsMap['vehicleModel'],
                                        "deposit": widget.goodsMap['deposit'],
                                        "depositType": widget.goodsMap['depositType'],
                                        "price": widget.goodsMap['price'],
                                        "priceUnit": widget.goodsMap['priceUnit'],
                                        "type": widget.goodsMap['type'],
                                        "remark": widget.goodsMap['remark'],
                                        "insurance": widget.goodsMap['insurance'],
                                        "sortCode": widget.goodsMap['sortCode'],
                                        "driverId":  dataList[index]['driverId']
                                      },
                                          (responseData) {
                                            BrnToast.show("指派成功", context);
                                            Navigator.pushAndRemoveUntil(
                                              context,
                                              MaterialPageRoute(builder: (context) => TabbarView(pateIndex: 2,)), // 推入第二个页面
                                                  (route) => false, // 从栈中移除所有页面，包括当前页面和第一个页面
                                            );
                                      },
                                    );
                                  }else {
                                    Navigator.push(context, FadeRoute(
                                        page: SelectSourceOfGoods(
                                          carMap: dataList[index],)));
                                  }
                                },
                              ),

                              SizedBox(width: 8.w,),
                              GestureDetector(
                                child:  BrnTagCustom.buildBorderTag(
                                  tagText: '电话联系',
                                  textColor: MyColors.themeColor,
                                  borderColor: MyColors.themeColor,
                                  fontWeight: FontWeight.w600,
                                  borderWidth: 1,
                                  fontSize: 12.sp,
                                  tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                  textPadding: EdgeInsets.all(6),
                                ),
                                onTap: (){
                                  _makePhoneCall(dataList[index]['phoneNum']);
                                },
                              ),
                            ],
                          ),
                        ),

                      ],
                    ),
                  );
                }),
          )
        ],
      ),
    );


  }
}
